<script setup>
import {getUserOrder, updateOrderStatus} from '@/apis/order'
import {onMounted, ref, onUnmounted} from 'vue';
import dayjs from "dayjs";
import {ElMessage, ElMessageBox} from "element-plus";
import {saveEvaluation} from "@/apis/goods";
// import { useCountDown } from '@/composables/useCountDown';

// const { returnFormaTime } = useCountDown()
// tab列表
const tabTypes = [
  {name: "all", label: "全部订单"},
  {name: "unpay", label: "待付款"},
  {name: "deliver", label: "待发货"},
  {name: "receive", label: "待收货"},
  {name: "comment", label: "待评价"},
  {name: "complete", label: "已完成"},
  {name: "cancel", label: "已取消"}
]

const formatTabType = (tabType) => {
  const tabTypeMap = {
    "all": null,
    "unpay": 0,
    "deliver": 1,
    "receive": 2,
    "comment": 3,
    "complete": 4,
    "cancel": 5,
  }
  return tabTypeMap[tabType]
}

// 订单列表
const orderList = ref([])
const total = ref(0)
const params = ref({
  status: null,
  pageNum: 1,
  pageSize: 2
})
let timer;

const getOrderList = async () => {
  const res = await getUserOrder(params.value)
  orderList.value = res.data.list
  total.value = res.data.total
}

onMounted(() => {
  getOrderList()
  // 开始定时器
  startCountdownTimer()
})

// 开始倒计时的函数
const startCountdownTimer = () => {
  timer = setInterval(updateCountdown, 1000)
}

// 更新倒计时
const updateCountdown = () => {
  orderList.value.forEach(order => {
    if (order.status === 0 && order.countdown > 0) {
      order.countdown -= 1000; // 每秒减少1000毫秒
    }
  });
}

// 清除定时器
onUnmounted(() => {
  clearInterval(timer);
});

// tab切换
const tabChange = (type) => {
  console.log(type)
  params.value.status = formatTabType(type)
  getOrderList()
}

// 页数切换
const pageChange = (pageNum) => {
  params.value.pageNum = pageNum
  getOrderList()
}

// 创建格式化函数
const formatPayStatus = (payState) => {
  const stateMap = {
    0: '待付款',
    1: '待发货',
    2: '待收货',
    3: '待评价',
    4: '已完成',
    5: '已取消'
  }
  return stateMap[payState]
}

// 格式化倒计时显示
const formatCountdown = (seconds) => {
  return dayjs.unix(seconds / 1000).format('mm分ss秒');
};

// const time = ref(1600)
const defaultTab = ref("all")

const showConfirmDelivery = ref(false);
// 确认收货
const confirmDelivery = async (order) => {
  await updateOrderStatus(order.id, 3);
  ElMessage.success(`订单【${order.orderNo}】收货成功！`);
  showConfirmDelivery.value = false;
  await getOrderList();
};

// 取消订单
const updateStatus = async (order) => {
  await updateOrderStatus(order.id, 5)
  ElMessage.success("订单【" + order.orderNo + "】取消成功！")
  await getOrderList()
}

// 评价商品
// 在 setup 中添加一个变量来控制对话框的显示和存储每个商品的评价内容
const showEvaluatingDialog = ref(false);
const evaluationData = ref([]);

// 在 showEvaluating 方法中设置对话框显示，并初始化评价内容
const showEvaluating = (order) => {
  // 初始化评价内容，每个商品的评价内容为空字符串
  order.goods.forEach(good => {
    const evaluatingContents = ref({
      id: '',
      name: '',
      evaluationInfo: '',
      orderId: ''
    }); // 用于存储每个商品的评价内容
    evaluatingContents.value.orderId = order.id;
    evaluatingContents.value.id = good.id;
    evaluatingContents.value.name = good.name;
    evaluatingContents.value.evaluationInfo = '';
    evaluationData.value.push(evaluatingContents.value);
  });
  showEvaluatingDialog.value = true; // 显示对话框
};

// 提交评价
const submitEvaluation = async () => {
  try {
    // 检查是否每个商品都已经填写了评价内容
    const hasEmptyEvaluation = evaluationData.value.some(evaluation => !evaluation.evaluationInfo.trim());

    if (hasEmptyEvaluation) {
      // 如果有未填写的评价内容，则提示用户填写评价
      ElMessage.error("请填写所有商品的评价内容！");
      return;
    }

    // 调用后端 API 提交评价
    const { data } = await saveEvaluation(evaluationData.value);

    // 提交成功后关闭对话框
    showEvaluatingDialog.value = false;
    // 这里可以添加一些成功提示或者重新加载订单列表等操作
    ElMessage.success(data.msg)
    await getOrderList()
  } catch (error) {
    console.error("提交评价时出错：", error);
    // 这里可以添加一些错误处理，比如显示错误提示
  }
};

const clearEvaluation = () => {
  evaluationData.value = [];
  showEvaluatingDialog.value = false
}

// 查看评价
const showEvaluationInfoModel = ref(false)
const orderGoodsEvaluations = ref([])
const showEvaluationInfo = (order) => {
  order.goods.forEach(goods => {
    orderGoodsEvaluations.value.push({
      goodsId: goods.id,
      goodsName: goods.name,
      evaluationContent: goods.evaluations[0].evaluationInfo,
      evaluationTime: goods.evaluations[0].createTime
    })
  })
  console.log(orderGoodsEvaluations.value)
  showEvaluationInfoModel.value = true
}

const clearGoodsEvaluation = () => {
  orderGoodsEvaluations.value = []
  showEvaluationInfoModel.value = false
}

</script>

<template>
  <!-- {{ returnFormaTime(time) }} -->
  <div class="order-container">
    <el-tabs @tab-change="tabChange" v-model="defaultTab">
      <!-- tab切换 -->
      <el-tab-pane v-for="item in tabTypes" :name="item.name" :key="item.name" :label="item.label"/>

      <div class="main-container">
        <div class="holder-container" v-if="orderList.length === 0">
          <el-empty description="暂无订单数据"/>
        </div>
        <div v-else>
          <!-- 订单列表 -->
          <div class="order-item" v-for="order in orderList" :key="order.id">
            <div class="head">
              <span>下单时间：{{ order.createTime }}</span>
              <span>订单编号：{{ order.orderNo }}</span>
              <!-- 未付款，倒计时时间还有 -->
              <span class="down-time" v-if="order.status === 0">
                                <i class="iconfont icon-down-time"></i>
                                <b>付款截止: {{ formatCountdown(order.countdown) }}</b>
                            </span>
            </div>
            <div class="body">
              <div class="column goods">
                <ul>
                  <li v-for="item in order.goods" :key="item.id">
                    <a class="image" href="javascript:;">
                      <img :src="item.picture" alt=""/>
                    </a>
                    <div class="info">
                      <p class="name ellipsis-2">
                        {{ item.name }}
                      </p>
                      <p class="attr ellipsis">
                        <span>{{ item.attrsText }}</span>
                      </p>
                    </div>
                    <div class="price">¥{{ item.price?.toFixed(2) }}</div>
                    <div class="count">x{{ item.goodsNum }}</div>
                  </li>
                </ul>
              </div>
              <div class="column state">
                <p>{{ formatPayStatus(order.status) }}</p>
                <!--                <p v-if="order.status === 2">-->
                <!--                  <a href="javascript:;" class="green">查看物流</a>-->
                <!--                </p>-->
                <p v-if="order.status === 3">
                  <a href="javascript:;" class="green" @click="showEvaluating(order)">评价商品</a>
                </p>
                <el-dialog title="商品评价" @close="clearEvaluation" :destroy-on-close="true"
                           v-model="showEvaluatingDialog">
                  <!-- 遍历订单中的每个商品，为每个商品都添加一个输入框 -->
                  <div v-for="evaluation in evaluationData" :key="evaluation.id" style="margin-bottom: 10px;">
                    <el-input
                        v-model="evaluation.evaluationInfo"
                        type="textarea"
                        :rows="5"
                        :placeholder="'请输入对商品【' + evaluation.name + '】的评价内容'"
                        autosize
                    ></el-input>
                  </div>
                  <span slot="footer" style="margin-left: 460px">
                    <el-button @click="clearEvaluation">取消</el-button>
                    <el-button type="primary" @click="submitEvaluation">提交</el-button>
                  </span>
                </el-dialog>
                <p v-if="order.status === 4">
                  <a href="javascript:;" class="green" @click="showEvaluationInfo(order)">查看评价</a>
                </p>
                <el-dialog title="查看评价" @close="clearGoodsEvaluation" v-model="showEvaluationInfoModel">
                  <div v-if="orderGoodsEvaluations.length > 0" v-for="goodsEvaluation in orderGoodsEvaluations" :key="goodsEvaluation.goodsId" style="margin-bottom: 20px;">
                    <ul>
                      <li >
                        <p>商品名称：{{ goodsEvaluation.goodsName }}</p>
                        <p>评价时间：{{ goodsEvaluation.evaluationTime }}</p>
                        <p>评价内容：{{ goodsEvaluation.evaluationContent }}</p>
                      </li>
                    </ul>
                  </div>
                </el-dialog>
              </div>
              <div class="column amount">
                <p class="red">¥{{ order.amount?.toFixed(2) }}</p>
                <p>（含运费：¥{{ order.postFee?.toFixed(2) }}）</p>
                <p>在线支付</p>
              </div>
              <div class="column action">
                <el-button v-if="order.status === 0" @click="$router.push(`/pay?id=${order.id}`)" type="primary"
                           size="small">
                  立即付款
                </el-button>
                <el-button v-if="order.status === 2" @click="showConfirmDelivery = true" type="primary" size="small">
                  确认收货
                </el-button>
                <el-dialog title="是否确认收货" v-model="showConfirmDelivery">
                  <p>订单【{{ order.orderNo }}}】</p>
                  <!-- 确定和取消按钮 -->
                  <template #footer>
                  <span class="dialog-footer">
                  <el-button @click="showConfirmDelivery = false">取消</el-button>
                  <el-button type="primary" @click="confirmDelivery(order)">确定</el-button>
                  </span>
                  </template>
                </el-dialog>
                <p><a @click="$router.push(`/member/order/detail/${order.id}`)" href="javascript:;">查看详情</a></p>
                <p v-if="[1, 2, 3, 4].includes(order.status)">
                  <a href="javascript:;" @click="$router.push(`/checkout?orderId=${order.id}`)">再次购买</a>
                </p>
                <!--                <p v-if="[3, 4].includes(order.status)">-->
                <!--                  <a href="javascript:;">申请售后</a>-->
                <!--                </p>-->
                <p v-if="order.status === 0">
                  <el-popconfirm title="确认取消订单吗?"
                                 confirm-button-text="确认"
                                 cancel-button-text="取消"
                                 @confirm="updateStatus(order)">
                    <template #reference>
                      <a href="javascript:;">取消订单</a>
                    </template>
                  </el-popconfirm>
                </p>
              </div>
            </div>
          </div>
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination @current-change="pageChange" :total="total" :page-size="params.pageSize" background
                           layout="prev, pager, next"/>
          </div>
        </div>
      </div>

    </el-tabs>
  </div>
</template>

<style scoped lang="scss">
.order-container {
  padding: 10px 20px;

  .pagination-container {
    display: flex;
    justify-content: center;
  }

  .main-container {
    min-height: 500px;

    .holder-container {
      min-height: 500px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.order-item {
  margin-bottom: 20px;
  border: 1px solid #f5f5f5;

  .head {
    height: 50px;
    line-height: 50px;
    background: #f5f5f5;
    padding: 0 20px;
    overflow: hidden;

    span {
      margin-right: 20px;

      &.down-time {
        margin-right: 0;
        float: right;

        i {
          vertical-align: middle;
          margin-right: 3px;
        }

        b {
          vertical-align: middle;
          font-weight: normal;
        }
      }
    }

    .del {
      margin-right: 0;
      float: right;
      color: #999;
    }
  }

  .body {
    display: flex;
    align-items: stretch;

    .column {
      border-left: 1px solid #f5f5f5;
      text-align: center;
      padding: 20px;

      > p {
        padding-top: 10px;
      }

      &:first-child {
        border-left: none;
      }

      &.goods {
        flex: 1;
        padding: 0;
        align-self: center;

        ul {
          li {
            border-bottom: 1px solid #f5f5f5;
            padding: 10px;
            display: flex;

            &:last-child {
              border-bottom: none;
            }

            .image {
              width: 70px;
              height: 70px;
              border: 1px solid #f5f5f5;
            }

            .info {
              width: 220px;
              text-align: left;
              padding: 0 10px;

              p {
                margin-bottom: 5px;

                &.name {
                  height: 38px;
                }

                &.attr {
                  color: #999;
                  font-size: 12px;

                  span {
                    margin-right: 5px;
                  }
                }
              }
            }

            .price {
              width: 100px;
            }

            .count {
              width: 80px;
            }
          }
        }
      }

      &.state {
        width: 120px;

        .green {
          color: $xtxColor;
        }
      }

      &.amount {
        width: 200px;

        .red {
          color: $priceColor;
        }
      }

      &.action {
        width: 140px;

        a {
          display: block;

          &:hover {
            color: $xtxColor;
          }
        }
      }
    }
  }
}
</style>